package com.vf.cloud.api.biz.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.vf.cloud.common.constant.Cache;
import com.vf.cloud.common.datasource.annotation.Tx;
import com.vf.cloud.common.domain.Config;
import com.vf.cloud.common.util.R;
import com.vf.cloud.common.util.UuidUtil;
import com.vf.cloud.server.colony.MasterServer;
import com.vf.cloud.server.colony.NodeServer;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
@RestController
@RequestMapping("/config")
public class ConfigController {

	@Tx
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public R<Config> save(Config model) {
		try {

			Config c = Config.dao.findById(model.getId());
			if (c == null) {
				model.setId("VFCloud_2022");
				if (model.save()) {
					return R.ok(model);
				} else {
					return R.failed("保存失败！");
				}
			}
			if (model.update()) {
				return R.ok(model);
			} else {
				return R.failed("更新失败！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return R.failed(e.getMessage());
		}
	}

	@Tx
	@RequestMapping(value = "/getConfig", method = RequestMethod.GET)
	public R<Config> getConfig() throws Exception {
		try {
			Config config = Config.dao.findById("VFCloud_2022");
			if (config == null) {
				config = new Config();
				config.setId("VFCloud_2022");
				config.setLocalPwd(UuidUtil.genCode());
				config.save();
			}
			return R.ok(config);
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

	@RequestMapping(value = "/restart", method = RequestMethod.GET)
	public R<String> restart() throws Exception {
		try {

			Config config = Config.dao.findById("VFCloud_2022");
			if (config != null) {
				MasterServer.getInstance().restart(config);
				NodeServer.getInstance().restart(config);
				Cache.config = config;
				return R.ok("发送指令成功，请稍后.");
			}
			return R.failed();
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

}
